<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      http://www.dbshop.net/
 * @copyright Copyright (c) 2012-2017 DBShop.net Inc. (http://www.dbshop.net)
 * @license   http://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风
 *
 */

namespace Dbapi\Model;

use Zend\Db\TableGateway\AbstractTableGateway;
use \Zend\Db\Adapter\AdapterAwareInterface;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Expression;
use Dbapi\Model\ApiGoods as dbshopCheckInData;

class ApiGoodsTable extends AbstractTableGateway implements AdapterAwareInterface
{
    protected $table = 'dbshop_goods';

    public function setDbAdapter(Adapter $adapter)
    {
        $this->adapter     = $adapter;
        $this->initialize();
    }
    /**
     * 商品列表信息（分页）
     * @param array $array
     * @return mixed
     */
    public function goodsListPage(array $array)
    {
        //声明select实例及当前数据表
        $select = new Select(array('dbshop_goods'=>$this->table));

        $interTable = isset($array['inner']) ? $array['inner'] : array();
        $where      = isset($array['where']) ? $array['where'] : '';
        $limit      = $array['limit'];
        $offset     = isset($array['offset']) ? $array['offset'] : '';
        $goodsSort  = isset($array['order']) ? $array['order'] : '';
        //对$where进行过滤处理
        //$where  = dbshopCheckInData::whereGoodsData($where);
        //排序处理
        if(!is_array($goodsSort)) {
            $goodsSort = (!empty($goodsSort) and $goodsSort!='dbshop_goods.goods_id DESC') ? array((strpos($goodsSort, 'dbshop_goods.goods_shop_price')===false ? $goodsSort : new Expression($goodsSort)), 'dbshop_goods.goods_id DESC') : 'dbshop_goods.goods_id DESC';
        }
        //连接表 dbshop_goods_extend 及显示的取出的字段内容，之所以这样处理，因为下面分页处理时，如有两个表有同一个字段信息会报错
        $select->join(array('e'=>'dbshop_goods_extend'), 'dbshop_goods.goods_id=e.goods_id',
            array(
                'goods_name',
                'goods_info',
                'goods_body',
                'goods_extend_name',
                'goods_keywords',
                'goods_description',
                'goods_image_id'
            )
        );
        //连接表 dbshop_goods_in_class
        if(isset($interTable['goods_in_class'])) {
            $select->join(array('goods_in'=>'dbshop_goods_in_class'), 'goods_in.goods_id=dbshop_goods.goods_id',
                array(
                    'class_id',
                    'class_goods_sort',
                    'class_state',
                    'class_recommend'
                )
            );
        }
        //连接表 dbshop_goods_tag_in_goods
        if(isset($interTable['goods_tag_in_goods'])) {
            $select->join(array('goods_tag_in'=>'dbshop_goods_tag_in_goods'), 'goods_tag_in.goods_id=dbshop_goods.goods_id',
                array(
                    'tag_id',
                    'tag_goods_sort'
                )
            );
        }
        //连接表 dbshop_dbapi_goods
        if(isset($interTable['dbshop_dbapi_goods'])) {
            $select->join(array('goods_api'=>'dbshop_dbapi_goods'), 'goods_api.goods_id=dbshop_goods.goods_id',
                array(
                    'dbapi_goods_id',
                    'dbapi_goods_code',
                    'dbapi_goods_sort'
                )
            );
        }

        $subSql = '';
        if(isset($array['group_id']) and $array['group_id'] > 0) {
            $subSql = ',(SELECT gp.goods_user_group_price FROM dbshop_goods_usergroup_price as gp WHERE gp.goods_id=dbshop_goods.goods_id and gp.user_group_id='.$array['group_id'].' and gp.goods_color=\'\' and gp.goods_size=\'\' and gp.adv_spec_tag_id=\'\') as group_price';
        }
        //子查询设定处理
        $select->columns(array('*', new Expression('
    	(SELECT i.goods_thumbnail_image FROM dbshop_goods_image as i WHERE i.goods_image_id=e.goods_image_id) as goods_thumbnail_image,
    	(SELECT in_c.class_id FROM dbshop_goods_in_class as in_c WHERE in_c.goods_id=dbshop_goods.goods_id and in_c.class_state=1 LIMIT 1) as one_class_id,
    	(SELECT SUM(og.buy_num) FROM dbshop_order_goods AS og INNER JOIN dbshop_order as do ON do.order_id=og.order_id WHERE og.goods_id=dbshop_goods.goods_id and do.order_state!=0) AS buy_num,
    	(SELECT count(uf.favorites_id) FROM dbshop_user_favorites AS uf WHERE uf.goods_id=dbshop_goods.goods_id) AS favorites_num
    	'.$subSql)));

        if(!empty($where)) $select->where($where);
        if(!empty($goodsSort)) $select->order($goodsSort);
        $select->limit($limit);
        if(!empty($offset)) $select->offset($offset);

        $resultSet = $this->selectWith($select);

        return $resultSet->toArray();
    }
    /**
     * 商品搜索
     * @param array $array
     * @return mixed
     */
    public function searchGoods (array $array)
    {
        $select     = new Select(array('dbshop_goods'=>$this->table));

        $where      = dbshopCheckInData::whereGoodsData($array['where']);
        $goodsSort  = $array['order'];
        $limit      = $array['limit'];
        $offset     = $array['offset'];

        $goodsSort = !empty($goodsSort) ? (strpos($goodsSort, 'dbshop_goods.goods_shop_price')===false ? $goodsSort : new Expression($goodsSort)) : 'dbshop_goods.goods_id DESC';

        $subSql = '';
        if(isset($array['group_id']) and $array['group_id'] > 0) {
            $subSql = ',(SELECT gp.goods_user_group_price FROM dbshop_goods_usergroup_price as gp WHERE gp.goods_id=dbshop_goods.goods_id and gp.user_group_id='.$array['group_id'].' and gp.goods_color=\'\' and gp.goods_size=\'\' and gp.adv_spec_tag_id=\'\') as group_price';
        }

        $select->columns(array('*', new Expression('
        (SELECT i.goods_thumbnail_image FROM dbshop_goods_image as i WHERE i.goods_image_id=e.goods_image_id) as goods_thumbnail_image,
        (SELECT in_c.class_id FROM dbshop_goods_in_class as in_c WHERE in_c.goods_id=dbshop_goods.goods_id and in_c.class_state=1 LIMIT 1) as one_class_id,
        (SELECT SUM(og.buy_num) FROM dbshop_order_goods AS og INNER JOIN dbshop_order as do ON do.order_id=og.order_id WHERE og.goods_id=dbshop_goods.goods_id and do.order_state!=0) AS buy_num,
    	(SELECT count(uf.favorites_id) FROM dbshop_user_favorites AS uf WHERE uf.goods_id=dbshop_goods.goods_id) AS favorites_num'
        .$subSql)));
        $select->join(array('e'=>'dbshop_goods_extend'), 'e.goods_id=dbshop_goods.goods_id',
            array(
                'goods_name',
                'goods_info',
                'goods_body',
                'goods_extend_name',
                'goods_keywords',
                'goods_description',
                'goods_image_id'
            )
        );
        $select->where($where)->where('dbshop_goods.goods_class_have_true=1');
        $select->order($goodsSort);

        $select->limit($limit);
        $select->offset($offset);

        $resultSet = $this->selectWith($select);
        return $resultSet->toArray();
    }
}